#!/bin/sh
PATH=/bin:/usr/bin:/snap/bin
export PATH

# If a command fails then the deploy stops
set -e
cd /home/zyh/data/blogs

echo "LOG DATE:" $(date +"%Y-%m-%d %H:%M:%S")
DATE=`date '+%Y%m%d-%H%M%S'`
echo $DATE
LogNameDATE=`date '+%Y'`
LogFile='./log/log'$LogNameDATE'.log'

echo " " >> $LogFile
echo "———————————————–" >> $LogFile
echo "BACKUP DATE:" $(date +"%Y-%m-%d %H:%M:%S") >> $LogFile


printf "\033[0;32mDeploying updates to GitHub...\033[0m\n"

printf "\n\n"
printf "\033[0;32mPull note files ...\033[0m\n"

cd content/posts
BRANCH=master
git fetch
LOCAL=$(git log $BRANCH -n 1 --pretty=format:"%H")
echo $LOCAL
REMOTE=$(git log remotes/origin/$BRANCH -n 1 --pretty=format:"%H")
echo $REMOTE
if [ $LOCAL = $REMOTE ]; then
    echo "do nothing"
    cd ../../
    exit 1
else
    cd ../../
    echo $(expect pull.exp) | grep "pulling" >> $LogFile

    printf "\n\n"
    printf "\033[0;32mHugo build ...\033[0m\n"

    # clean Public folder
    printf "\033[0;32mclean Public folder ...\033[0m\n"
    cd public
    rm -r *
    cd ../

    # Build the project.
    echo $(hugo -t LoveIt)  >> $LogFile # if using a theme, replace with `hugo -t <YOURTHEME>`

    printf "\n\n"
    printf "\033[0;32mpush public ...\033[0m\n"

    # Go To Public folder
    cd public

    # Add changes to git.
    if [ -n "$(git status -s)" ];then
      git add ./
      # Commit changes.
      msg="update $(date)"
      if [ -n "$*" ]; then
        msg="$*"
      fi
      git commit -m "$msg"

      cd ../

      echo $(expect push_main.exp) | grep "pushing" >> $LogFile
    else
      cd ../
      echo $(expect push_main.exp) | grep "pushing" >> $LogFile
    fi

    echo "———————————————–" >> $LogFile

    printf "\n\n"
    printf "\033[0;32mPush ...\033[0m\n"

    # Add changes to git.
    if [ -n "$(git status -s)" ];then
      git add ./
      # Commit changes.
      msg="update $(date)"
      if [ -n "$*" ]; then
        msg="$*"
      fi
      git commit -m "$msg"

      # Push source and build repos.
      expect push_master.exp
    fi

    printf "\n\n"
    printf "\033[0;32mDone\033[0m\n"
fi